package kuang.juc.assist3;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class SemaphoreDemo {
    //Semaphore：信号量
    public static void main(String[] args) {
        //允许的线程数量，模拟停车位     限流可以用到
        Semaphore semaphore = new Semaphore(3);
        for (int i = 1; i <= 6; i++) {
            int finalI=i;
            new Thread(()->{
                try {
                    //得到线程，获得停车位
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName()+"获得停车位");
                    //模拟停车3秒后离开
                    TimeUnit.SECONDS.sleep(finalI+2);
                    System.out.println(Thread.currentThread().getName()+"离开停车位");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    //释放线程，离开停车位
                    semaphore.release();
                }
            },String.valueOf(i)).start();
        }
    }
}
